package com.xds.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xds.common.utils.R;
import com.xds.gulimall.cart.feign.ProductFeign;
import com.xds.gulimall.cart.interceptor.CartInterceptor;
import com.xds.gulimall.cart.service.CatService;
import com.xds.gulimall.cart.to.UserInfoTo;
import com.xds.gulimall.cart.vo.CartItemVo;
import com.xds.gulimall.cart.vo.CartVo;
import com.xds.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author : baixu
 * @date : 16:48 2021/12/22
 */
@Service
@Slf4j
public class CatServiceImpl implements CatService {
    @Autowired
    private  ThreadPoolExecutor executor;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeign productFeign;
    private final String CART_PREFIX="gulimall:cart:";



    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps =getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = new CartItemVo();
        if (StringUtils.isEmpty(res)){
            //购物车无此商品
            //添加新商品

            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                //远程查询当前要天添加商品的详情
                R skuInfo = productFeign.getSkuInfo(skuId);
                SkuInfoVo vo = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //将商品添加到购物车

                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(vo.getSkuDefaultImg());
                cartItemVo.setPrice(vo.getPrice());
                cartItemVo.setTitle(vo.getSkuTitle());
                cartItemVo.setSkuId(skuId);
            },executor);

            CompletableFuture<Void> getSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> saleAttrValues = productFeign.getSkuSaleAttrValues(skuId);
                //远程查询sku的组合信息
                cartItemVo.setSkuAttrValues(saleAttrValues);
            }, executor);
            //等待所有的异步任务全部完成
            CompletableFuture.allOf(getSkuInfo, getSaleAttrValues).get();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
        }else {
            //购物车有此商品 修改数量即可
            CartItemVo vo = JSON.parseObject(res, CartItemVo.class);
            BeanUtils.copyProperties(vo,cartItemVo);
            cartItemVo.setCount(vo.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
        }

        return cartItemVo;
    }
    //获取购物车某个购物项
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(str, CartItemVo.class);
        return cartItemVo;
    }

    /**
     * 获取购物车
     * @return
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //登陆
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
            //如果还有临时购物车 并且没有合并 需要把临时购物车合并进去 并清除临时购物车数据
            List<CartItemVo> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems!=null){
                //临时购物车有数据 需要和登陆购物车数据合并 并且删除临时购物车数据
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清除临时购物车的数据
                clearCart(CART_PREFIX+userInfoTo.getUserKey());
            }
            //获取登陆购物车数据 包含合并临时购物车数据
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        }else {
            //没有登陆
            String cartKey=CART_PREFIX+userInfoTo.getUserKey();
            //获取临时购物车 所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    //获取要操作的购物车
    private  BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        String cartKey="";
        if (userInfoTo.getUserId()!=null){
            //登陆购物车
            cartKey=CART_PREFIX+userInfoTo.getUserId();
        }else {
            //临时购物车
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
    private List<CartItemVo> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!=null&&values.size()>0){
            List<CartItemVo> collect = values.stream().map(obj -> {
                String str= (String) obj;
                CartItemVo cartItemVo = JSON.parseObject(str, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
           return collect;
        }

        return null;
    }
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
//        cartOps.putIfAbsent(skuId.toString(),s);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
            //查询购物车里面的商品
            CartItemVo cartItem = getCartItem(skuId);
            cartItem.setCount(num);
            BoundHashOperations<String, Object, Object> cartOps = getCartOps();
            //序列化存入redis中
            String redisValue = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),redisValue);
        }
    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteIdCartInfo(Integer skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserItems() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId()==null){
            //没有登陆
            return null;
        }else {
            String cartKey=CART_PREFIX+userInfoTo.getUserId();
         return   getCartItems(cartKey).stream().filter(item->item.getCheck()).map(item->{
             item.setPrice(productFeign.getNewPrice(item.getSkuId()));
             System.out.println(item);
             return item;
         }).collect(Collectors.toList());
        }
    }
}

